<?php

namespace App\Api\Controllers\CustomerApplets;

use App\Http\Controllers\Auth\ResetPasswordController;
use App\Models\AliThirdConfig;
use Dingo\Api\Facade\Route;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Api\Controllers\CustomerApplets\BaseController;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayOpenAuthTokenAppRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionUploadRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionBuildQueryRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionDetailQueryRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniTemplateUsageQueryRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionOnlineRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionOfflineRequest;
use Alipayopen\Sdk\Request\AlipayOpenAppMiniTemplatemessageSendRequest;

use Alipayopen\Sdk\Request\AlipayOpenMiniVersionAuditedCancelRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionGrayCancelRequest;
use Alipayopen\Sdk\Request\AlipayOpenMiniVersionDeleteRequest;
use Alipayopen2019\Request\AlipayOpenMiniVersionAuditCancelRequest;

use Alipayopen2019\AopClient as AopClient2019;
use Alipayopen2019\Request\AlipayOpenMiniVersionAuditApplyRequest;
use Alipayopen2019\Request\AlipayOpenMiniBaseinfoQueryRequest;
use Alipayopen2019\Request\AlipayOpenMiniBaseinfoModifyRequest;
use Alipayopen2019\Request\AlipayOpenMiniCategoryQueryRequest;

use Alipayopen2019\Request\AlipayOpenAuthAppAesGetRequest;
use Alipayopen2019\Request\AlipayOpenAuthAppAesSetRequest;

class AliPayTicketController extends BaseController
{
    protected $customerAppletsRegisterWeApps = "customerapplets_fast_register_weapps";
    protected $customerAppletsAuthorizeAppid = "customerapplets_authorize_appids";
    protected $ali_appid; // 最新支付宝小程序的第三方应用的id

    // public function __construct()
    // {
    //     // 支付宝第三方参数
    //     $aliModel = new AliThirdConfig();
    //     $aliData = $aliModel->getInfo();
    //
    //     if (empty($aliData)) {
    //         return $this->sys_response(4002, '请先配置支付宝第三方参数');
    //     }
    //
    //     $this->ali_appid = $aliData->aliPay_applet_id;
    // }

    /**
     * 接收支付宝第三方应用授权回调数据
     * 并且返回对应的视图文件
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
     */
    public function message(Request $request)
    {

        //获取回调请求数据
        $requestAllRequest = $request->all();

        if (isset($requestAllRequest['app_id']) && isset($requestAllRequest['app_auth_code']) && !empty($requestAllRequest['app_id'])) {
            //这里是小程序授权到第三方应用平台之后的回调信息
            Log::info("支付宝授权小程序数组数据：".json_encode($requestAllRequest));

            $store_id = isset($requestAllRequest['store_id']) ? $requestAllRequest['store_id'] : "";

            $result = $this->aliPayOpenAuthTokenApp($requestAllRequest['app_id'], $requestAllRequest['app_auth_code'], $store_id);

            if ($result['status'] == 200) {
                //授权成功
                return view("webH5Mobile.authorizeSuccess");
            } else {
                return $result['message'];
            }
        } else {
            Log::info("支付宝小程序审核结果数据：".json_encode($requestAllRequest));
        }
    }

    /**
     * 封装换取应用授权令牌,获取成功，进行储存
     * @param $appId
     *        第三方应用appid
     * @param $app_auth_code
     *        app_auth_code
     * @param $store_id
     * @return array
     */
    public function aliPayOpenAuthTokenApp($appId, $app_auth_code, $store_id = null)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.auth.token.app";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenAuthTokenAppRequest();
            $request->setBizContent("{" .
                "\"grant_type\":\"authorization_code\"," .
                "\"code\":\"".$app_auth_code."\"" .
                "  }");
            $result = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                $tokens     = $result->$responseNode->tokens;

                $insertData = [];

                $authAppId  = "";
                foreach ($tokens as $key => $val) {
                    $userId           = $val->user_id;
                    $authAppId        = $val->auth_app_id;
                    $appAuthToken     = $val->app_auth_token;
                    $appRefreshToken  = $val->app_refresh_token;
                    $expiresIn        = $val->expires_in;
                    $reExpiresIn      = $val->re_expires_in;

                    //查询小程序的基础信息
                    $app_name = "";

                    $queryRequest  = new AlipayOpenMiniBaseinfoQueryRequest();
                    $queryResult   = $aop->execute($queryRequest, null, $appAuthToken);
                    $queryResponse = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
                    $queryResponseNode = $queryResult->$queryResponse->code;
                    if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                        if (isset($queryResult->$queryResponse->app_name)) {
                            $app_name = $queryResult->$queryResponse->app_name;
                        }
                    }

                    //获取或者设置商家小程序的aesKey密钥
                    $aesKey = "";
//                    $getAesKey = $this->aliPayOpenAuthAppAesGet($appId,$appAuthToken,$authAppId);
//                    if($getAesKey['status'] == 200){
//                        $aesKey = $getAesKey['aesKey'];
//                    }else{
//                        //进行设置aesKey密钥
//                        $setAesKey = $this->aliPayOpenAuthAppAesSet($appId,$appAuthToken,$authAppId);
//                        if($setAesKey['status'] == 200) {
//                            $aesKey = $setAesKey['aesKey'];
//                        }
//                    }
                    //说明是授权小程序成功
                    $authorizeAppidInfo = DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $appId,'AuthorizerAppid' => $authAppId,'applet_type' => 2])->first();
                    if (empty($authorizeAppidInfo)) {
                        array_push($insertData, [
                            'applet_name'                   => $app_name,
                            't_appid'                       => $appId,
                            'CreateTime'                    => time(),
                            'InfoType'                      => 'authorized',
                            'applet_type'                   => 2,
                            'AuthorizerAppid'               => $authAppId,
                            'AuthorizationCode'             => $appAuthToken,
                            'AuthorizationCodeExpiredTime'  => $expiresIn,
                            'PreAuthCode'                   => $appRefreshToken,
                            'authorizer_refresh_token'      => $appRefreshToken,
                            'aliPay_aes'                    => $aesKey,
                            'created_at'                    => date("Y-m-d H:i:s", time()),
                            'updated_at'                    => date("Y-m-d H:i:s", time())
                        ]);
                    } else {
                        DB::table($this->customerAppletsAuthorizeAppid)->where(['t_appid' => $appId,'AuthorizerAppid' => $authAppId,'applet_type' => 2])->update([
                            'applet_name'                   => $app_name,
                            'AuthorizationCode'             => $appAuthToken,
                            'AuthorizationCodeExpiredTime'  => $expiresIn,
                            'PreAuthCode'                   => $appRefreshToken,
                            'authorizer_refresh_token'      => $appRefreshToken,
                            'aliPay_aes'                    => $aesKey ? $aesKey : $authorizeAppidInfo->aliPay_aes,
                            'updated_at' => date("Y-m-d H:i:s", time())
                        ]);
                    }
                }

                if (!empty($insertData) && count($insertData) > 0) {
                    DB::table($this->customerAppletsAuthorizeAppid)->insert($insertData);
                }

                if ($store_id) {
                    $storeAppletInfo = DB::table("merchant_store_appid_secrets")->where(['store_id' => $store_id])->first();
                    if (!empty($storeAppletInfo)) {
                        DB::table("merchant_store_appid_secrets")->where(['store_id' => $store_id])->update([
                            'alipay_appid' => $authAppId,
                            'updated_at'   => date("Y-m-d H:i:s", time())
                        ]);
                    } else {
                        DB::table("merchant_store_appid_secrets")->insert([
                            'store_id'     => $store_id,
                            'alipay_appid' => $authAppId,
                            'created_at'   => date("Y-m-d H:i:s", time()),
                            'updated_at'   => date("Y-m-d H:i:s", time()),
                        ]);
                    }
                }

                return ['status' => 200,'message' => '授权成功','data' => ['user_id' => $userId,'auth_app_id' => $authAppId,'app_auth_token' => $appAuthToken,'app_refresh_token' => $appRefreshToken,'expires_in' => $expiresIn,'re_expires_in' => $reExpiresIn]];
            } else {
                return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 对外请求方法 构建小程序版本
     * 小程序基于模板上传版本
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function aliPayOpenMiniVersionUpload(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])) {
            return $this->responseDataJson(202, "门店id参数不可为空");
        }

        $storeInfo = DB::table("merchant_store_appid_secrets")->where(['store_id' => $requestAllData['store_id']])->first();

        if (empty($storeInfo)) {
            return $this->responseDataJson(202, "该门店appid信息不存在");
        }
        if (empty($storeInfo->alipay_appid)) {
            return $this->responseDataJson(202, "请先完善该门店支付宝小程序信息");
        }

        $authorizeAppId = $this->getAuthorizeAppId($storeInfo->alipay_appid);
        if (empty($authorizeAppId['t_appid'])) {
            return $this->responseDataJson(202, "请先完成该小程序在支付宝第三方应用平台上进行授权");
        }

        //小程序模板版本号
        if (!isset($requestAllData['template_version']) || empty($requestAllData['template_version'])) {
            return $this->responseDataJson(202, "小程序模板版本号不可为空");
        }
        //小程序模板id
        if (!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])) {
            return $this->responseDataJson(202, "小程序模板id不可为空");
        }

        //营业执照名称
//        if(!isset($requestAllData['license_name']) || empty($requestAllData['license_name'])){
//            return $this->responseDataJson(202,"营业执照名称不可为空");
//        }

        //营业执照有效期
//        if(!isset($requestAllData['license_valid_date']) || empty($requestAllData['license_valid_date'])){
//            return $this->responseDataJson(202,"营业执照有效期不可为空");
//        }

        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $authorizeAppId['t_appid'];
            $aop->method                = "alipay.open.mini.version.upload";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionUploadRequest();

            $request->setBizContent("{" .
                "\"template_version\":\"".$requestAllData['template_version']."\"," .
                "\"ext\":\"{\\\"extEnable\\\": true, \\\"ext\\\": {\\\"storeId\\\": \\\"".$requestAllData['store_id']."\\\"}, \\\"extPages\\\": {\\\"pages/index/index\\\": {\\\"defaultTitle\\\": \\\"\\\"}},\\\"window\\\": {\\\"defaultTitle\\\": \\\"\\\"}}\"," .
                "\"template_id\":\"".$requestAllData['template_id']."\"," .
                "\"app_version\":\"".$requestAllData['template_version']."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");

            $result = $aop->execute($request, null, $authorizeAppId['AuthorizationCode']);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {

                //小程序查询版本构建状态
//                $aliPayOpenMiniVersionBuildQuery = $this->aliPayOpenMiniVersionBuildQuery($authorizeAppId['t_appid'],$authorizeAppId['AuthorizationCode'],$requestAllData['template_version']);
//
//                if($aliPayOpenMiniVersionBuildQuery['status'] == 200){
//                    if($aliPayOpenMiniVersionBuildQuery['create_status'] == 6) {

                //小程序提交审核
//                        $aliPayOpenMiniVersionAuditApply = $this->aliPayOpenMiniVersionAuditApply($authorizeAppId['t_appid'],$authorizeAppId['AuthorizationCode'],$requestAllData['license_name'],$requestAllData['license_valid_date'],$requestAllData['template_version'],$requestAllData['store_applets_desc']);
//
//                        if($aliPayOpenMiniVersionAuditApply['status'] == 200){
//                            return $this->responseDataJson(200,'构建小程序版本成功|提交审核成功');
//                        }else{
//                            return $this->responseDataJson($aliPayOpenMiniVersionAuditApply['status'],$aliPayOpenMiniVersionAuditApply['message']);
//                        }

//                    }else{
//                        return $this->responseDataJson(202,"构建小程序版本成功|".'提交审核失败');
//                    }
//
//                }else{
//                    return $this->responseDataJson($aliPayOpenMiniVersionBuildQuery['status'],"构建小程序版本成功|".$aliPayOpenMiniVersionBuildQuery['message']);
//                }
                return $this->responseDataJson(200, '构建小程序版本成功，下一步：请进行提交审核');
            } else {
                return $this->responseDataJson(202, $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(202, $e->getMessage());
        }
    }

    /**
     * 对外请求方法 小程序提交审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenMiniVersionAuditApply(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['mini_app_id']) || empty($requestAllData['mini_app_id'])) {
            return $this->responseDataJson(202, "小程序appid不可为空");
        }

        if (!isset($requestAllData['app_version']) || empty($requestAllData['app_version'])) {
            return $this->responseDataJson(202, "小程序版本不可为空");
        }

        //营业执照名称
        if (!isset($requestAllData['license_name']) || empty($requestAllData['license_name'])) {
            return $this->responseDataJson(202, "营业执照名称不可为空");
        }

        //营业执照有效期
        if (!isset($requestAllData['license_valid_date']) || empty($requestAllData['license_valid_date'])) {
            return $this->responseDataJson(202, "营业执照有效期不可为空");
        }

        //小程序描述
        if (!isset($requestAllData['store_applets_desc']) || empty($requestAllData['store_applets_desc'])) {
            return $this->responseDataJson(202, "描述内容不可为空");
        }

        $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->first();

        if (empty($appletsInfo)) {
            return $this->responseDataJson(202, "该小程序暂未授权");
        }

        //先查询小程序 版本构建状态
        $aliPayOpenMiniVersionBuildQuery = $this->aliPayOpenMiniVersionBuildQuery($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['app_version']);
        if ($aliPayOpenMiniVersionBuildQuery['status'] == 200) {
            if ($aliPayOpenMiniVersionBuildQuery['create_status'] == 6) {
                $app_logo = isset($requestAllData['license']) ? $requestAllData['license'] : "";
                $app_english_name = isset($requestAllData['app_english_name']) ? $requestAllData['app_english_name'] : "";
                $app_slogan = isset($requestAllData['app_slogan']) ? $requestAllData['app_slogan'] : "";
                $app_desc = isset($requestAllData['app_desc']) ? $requestAllData['app_desc'] : "";
                //小程序提交审核
                $aliPayOpenMiniVersionAuditApply = $this->aliPayOpenMiniVersionAuditApply($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['license_name'], $requestAllData['license_valid_date'], $requestAllData['app_version'], $requestAllData['store_applets_desc'], $app_logo, $app_english_name, $app_slogan, $app_desc);

                if ($aliPayOpenMiniVersionAuditApply['status'] == 200) {
                    return $this->responseDataJson(200, '提交审核代码成功');
                } else {
                    return $this->responseDataJson($aliPayOpenMiniVersionAuditApply['status'], $aliPayOpenMiniVersionAuditApply['message']);
                }
            } else {
                return $this->responseDataJson(202, '授权成功,版本暂未构建');
            }
        } else {
            return $this->responseDataJson(202, $aliPayOpenMiniVersionBuildQuery['message']);
        }
    }

    /**
     * 封装 小程序查询版本构建状态
     * @param $appId
     *        第三方应用appid
     * @param $app_auth_token
     *        app_auth_token
     * @param $app_version
     *        小程序版本号
     * @return array
     */
    public function aliPayOpenMiniVersionBuildQuery($appId, $app_auth_token, $app_version)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.version.build.query";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionBuildQueryRequest();
            $request->setBizContent("{" .
                "\"app_version\":\"".$app_version."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");
            $result = $aop->execute($request, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                $create_status = $result->$responseNode->create_status;
                return ['status' => 200,'message' => '查询成功','create_status' => $create_status];
            } else {
                return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 小程序提交审核
     * @param $appId
     *        第三方应用appid
     * @param $app_auth_token
     *        app_auth_token
     * @return array
     */
    public function aliPayOpenMiniVersionAuditApply($appId, $app_auth_token, $license_name, $license_valid_date, $app_version, $version_desc, $app_logo = null, $app_english_name = null, $app_slogan = null, $app_desc = null)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.version.audit.apply";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionAuditApplyRequest();
            $request->setLicenseName($license_name);
            //营业执照有效期，格式为yyyy-MM-dd，9999-12-31表示长期，部分小程序类目需要提交，参照https://opendocs.alipay.com/mini/operation/material中是否需要营业执照信息，如果不填默认采用当前小程序营业执照有效期
            $request->setLicenseValidDate($license_valid_date);
            $request->setAppVersion($app_version);
            if (!empty($app_desc)) {
                $request->setAppDesc($version_desc);
            }
            $request->setVersionDesc($version_desc);
            if (!empty($app_logo)) {
                $request->setAppLogo("@".$app_logo);
            }
            if (!empty($app_english_name)) {
                $request->setAppEnglishName($app_english_name);
            }
            if (!empty($app_slogan)) {
                $request->setAppSlogan($app_slogan);
            }

            $request->setMemo("一款外卖小程序");
            $request->setRegionType("CHINA");
            $result = $aop->execute($request, null, $app_auth_token);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return ['status' => 200,'message' => '提交审核成功'];
            } else {
                if ($result->$responseNode->sub_code == "DEFAULT_LOGO") {
                    return ['status' => 202,'message' => "不能使用默认LOGO提审，请上传小程序logo"];
                } else {
                    return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
                }
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 对外请求方法 查询使用模板的小程序列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenMiniTemplateUsageQuery(Request $request)
    {
        $requestAllData = $request->all();

        //TODO:2021002108609082 这个值暂时可以先写死
        $appletsInfo    = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => '2021002108609082'])->first();
        if (!$appletsInfo) {
            return response()->json([
                'status'  => 202,
                'message' => "暂无数据",
                'data'    => []
            ]);
        }

        $result = $this->aliPayOpenMiniTemplateUsageQuery($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, "2021002108609082", $requestAllData['page']);
        $data = [];
        if ($result['status'] == 200) {
            $data = $result['data'];
            foreach ($data as $key => $val) {
                $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $val->mini_app_id])->first();
                if (!empty($appletsInfo)) {
                    $aliPayOpenMiniVersionDetailQuery = $this->aliPayOpenMiniVersionDetailQuery($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $val->app_version);

                    if ($aliPayOpenMiniVersionDetailQuery['status'] == 200) {
                        $aliPayOpenMiniVersionDetail = $aliPayOpenMiniVersionDetailQuery['data'];

                        $val->app_name      = $aliPayOpenMiniVersionDetail['app_name'];
                        $val->status        = $aliPayOpenMiniVersionDetail['status'];
                        $val->status_name   = $aliPayOpenMiniVersionDetail['status_name'];
                        $val->reject_reason = $aliPayOpenMiniVersionDetail['reject_reason'];
                    } else {
                        $val->app_name = $aliPayOpenMiniVersionDetailQuery['message'];
                        $val->status   = $aliPayOpenMiniVersionDetailQuery['message'];
                        $val->status_name   = "";
                        $val->reject_reason = "";
                    }
                } else {
                    $val->app_name = "数据库未查询到，未进行授权";
                    $val->status   = "数据库未查询到，未进行授权";
                    $val->status_name   = "";
                    $val->reject_reason = "";
                }
            }
        }

        return response()->json([
            'status'  => 200,
            'message' => "获取成功",
            'data'    => $data,
            'total_count' => 500,
            'page'  => (int)$requestAllData['page'],
            't' => (int)$requestAllData['count'],
        ]);
    }

    /**
     * 封装 查询使用模板的小程序列表
     * @param $appId
     *        第三方应用appid
     * @param $app_auth_token
     *        app_auth_token
     * @param $template_id
     *        模板id
     * @param $page
     *        当前查询的页数，以10条数据为一页
     * @return array
     */
    public function aliPayOpenMiniTemplateUsageQuery($appId, $app_auth_token, $template_id, $page)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.template.usage.query";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniTemplateUsageQueryRequest();

            $request->setBizContent("{" .
                "\"template_id\":\"".$template_id."\"," .
                "\"page_num\":".$page."," .
                "\"page_size\":10" .
                "  }");

            $result = $aop->execute($request, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                if (isset($result->$responseNode->template_usage_info_list) && !empty($result->$responseNode->template_usage_info_list)) {
                    $template_usage_info_list = $result->$responseNode->template_usage_info_list;
                    return ['status' => 200,'message' => '查询成功','data' => $template_usage_info_list];
                } else {
                    return ['status' => 200,'message' => '查询成功','data' => []];
                }
            } else {
                return ['status' => 40001,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 40002,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 小程序版本详情查询
     * @param $appId
     *        第三方应用appid
     * @param $app_auth_token
     *        app_auth_token
     * @param $app_version
     *        小程序版本号
     * @return array
     */
    public function aliPayOpenMiniVersionDetailQuery($appId, $app_auth_token, $app_version)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.version.detail.query";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionDetailQueryRequest();
            $request->setBizContent("{" .
                "\"app_version\":\"".$app_version."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");

            $result = $aop->execute($request, null, $app_auth_token);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                $applets = [];

                if (isset($result->$responseNode->app_name)) {
                    $applets['app_name'] = $result->$responseNode->app_name;
                } else {
                    $applets['app_name'] = "";
                }

                if (isset($result->$responseNode->status)) {
                    switch ($result->$responseNode->status) {
                        case "INIT":
                            $applets['status_name'] = "开发中";
                            break;
                        case "AUDITING":
                            $applets['status_name'] = "审核中";
                            break;
                        case "WAIT_RELEASE":
                            $applets['status_name'] = "审核通过";
                            break;
                        case "AUDIT_REJECT":
                            $applets['status_name'] = "审核驳回";
                            break;
                        case "RELEASE":
                            $applets['status_name'] = "已上架";
                            break;
                        case "GRAY":
                            $applets['status_name'] = "灰度中";
                            break;
                        case "OFFLINE":
                            $applets['status_name'] = "下架";
                            break;
                    }
                    $applets['status'] = $result->$responseNode->status;
                } else {
                    $applets['status'] = "";
                    $applets['status_name'] = "";
                }

                if (isset($result->$responseNode->reject_reason)) {
                    $applets['reject_reason'] = $result->$responseNode->reject_reason;
                } else {
                    $applets['reject_reason'] = "";
                }

                return ['status' => 200,'message' => '查询成功','data' => $applets];
            } else {
                return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 对外请求方法 小程序进行发布上架或者下架
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenMiniVersionOnline(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['mini_app_id']) || empty($requestAllData['mini_app_id'])) {
            return $this->responseDataJson(202, "小程序appid不可为空");
        }

        if (!isset($requestAllData['app_version']) || empty($requestAllData['app_version'])) {
            return $this->responseDataJson(202, "小程序版本不可为空");
        }

        if (!isset($requestAllData['type']) || empty($requestAllData['type'])) {
            return $this->responseDataJson(202, "类型不可为空");
        }

        $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->first();

        if (empty($appletsInfo)) {
            return $this->responseDataJson(202, "该小程序暂未授权");
        }

        if ($requestAllData['type'] == 1) {
            //小程序上架
            $aliPayOpenMiniVersionAuditApply = $this->aliPayOpenMiniVersionOnline($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['app_version']);

            if ($aliPayOpenMiniVersionAuditApply['status'] == 200) {
                return $this->responseDataJson(200, '小程序上架成功');
            } else {
                return $this->responseDataJson($aliPayOpenMiniVersionAuditApply['status'], $aliPayOpenMiniVersionAuditApply['message']);
            }
        } else {
            //小程序下架
            $aliPayOpenMiniVersionAuditApply = $this->aliPayOpenMiniVersionOffline($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['app_version']);

            if ($aliPayOpenMiniVersionAuditApply['status'] == 200) {
                return $this->responseDataJson(200, '小程序下架成功');
            } else {
                return $this->responseDataJson($aliPayOpenMiniVersionAuditApply['status'], $aliPayOpenMiniVersionAuditApply['message']);
            }
        }
    }

    /**
     * 封装 小程序进行发布上架
     * @param $appId
     * @param $app_auth_token
     * @param $app_version
     * @return array
     */
    public function aliPayOpenMiniVersionOnline($appId, $app_auth_token, $app_version)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.version.online";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionOnlineRequest();
            $request->setBizContent("{" .
                "\"app_version\":\"".$app_version."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");

            $result = $aop->execute($request, null, $app_auth_token);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return ['status' => 200,'message' => '上架成功'];
            } else {
                return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 小程序进行下架
     * @param $appId
     * @param $app_auth_token
     * @param $app_version
     * @return array
     */
    public function aliPayOpenMiniVersionOffline($appId, $app_auth_token, $app_version)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.version.offline";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenMiniVersionOfflineRequest();
            $request->setBizContent("{" .
                "\"app_version\":\"".$app_version."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");

            $result = $aop->execute($request, null, $app_auth_token);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return ['status' => 200,'message' => '下架成功'];
            } else {
                return ['status' => 202,'message' => $result->$responseNode->msg.'|'.$result->$responseNode->sub_code.'|'.$result->$responseNode->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 对外请求方法 小程序查询信息或者修改小程序基础信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenMiniBaseInfoQuery(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['mini_app_id']) || empty($requestAllData['mini_app_id'])) {
            return $this->responseDataJson(202, "小程序appid不可为空");
        }

        if (!isset($requestAllData['type']) || empty($requestAllData['type'])) {
            return $this->responseDataJson(202, "类型不可为空");
        }

        $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->first();

        if (empty($appletsInfo)) {
            return $this->responseDataJson(202, "该小程序暂未授权");
        }

        if ($requestAllData['type'] == 1) {
            //查询小程序信息
            $result = $this->aliPayOpenMiniBaseInfoQuery($appletsInfo->t_appid, $appletsInfo->AuthorizationCode);
            if ($result['status'] == 200) {
                //查询小程序类目信息
                $resultCategory = $this->aliPayOpenMiniCategoryQuery($appletsInfo->t_appid, $appletsInfo->AuthorizationCode);
                if ($resultCategory['status'] == 200) {
                    $result['data']['mini_category_list'] = $resultCategory['data'];
                    return $this->responseDataJson(200, '查询成功', $result['data']);
                } else {
                    return $this->responseDataJson($resultCategory['status'], $resultCategory['message']);
                }
            } else {
                return $this->responseDataJson($result['status'], $result['message']);
            }
        } else {
            //修改小程序信息
            $result = $this->aliPayOpenMiniBaseInfoModify($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData);
            if ($result['status'] == 200) {
                return $this->responseDataJson(200, '小程序修改成功');
            } else {
                return $this->responseDataJson($result['status'], $result['message']);
            }
        }
    }

    /**
     * 封装 查询小程序基础信息
     * @param $appId
     * @param $app_auth_token
     * @return array
     */
    public function aliPayOpenMiniBaseInfoQuery($appId, $app_auth_token)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.baseinfo.query";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $queryRequest = new AlipayOpenMiniBaseinfoQueryRequest();
            $queryResult = $aop->execute($queryRequest, null, $app_auth_token);
            $queryResponse = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
            $queryResponseNode = $queryResult->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                $data = [];
                if (isset($queryResult->$queryResponse->app_name) && !empty($queryResult->$queryResponse->app_name)) {
                    $data['app_name'] = $queryResult->$queryResponse->app_name;
                } else {
                    $data['app_name'] = "";
                }
                if (isset($queryResult->$queryResponse->app_english_name) && !empty($queryResult->$queryResponse->app_english_name)) {
                    $data['app_english_name'] = $queryResult->$queryResponse->app_english_name;
                } else {
                    $data['app_english_name'] = "";
                }
                if (isset($queryResult->$queryResponse->app_slogan) && !empty($queryResult->$queryResponse->app_slogan)) {
                    $data['app_slogan'] = $queryResult->$queryResponse->app_slogan;
                } else {
                    $data['app_slogan'] = "";
                }
                if (isset($queryResult->$queryResponse->app_logo) && !empty($queryResult->$queryResponse->app_logo)) {
                    $data['app_logo'] = $queryResult->$queryResponse->app_logo;
                } else {
                    $data['app_logo'] = "";
                }
                if (isset($queryResult->$queryResponse->category_names) && !empty($queryResult->$queryResponse->category_names)) {
                    $data['category_names'] = $queryResult->$queryResponse->category_names;
                } else {
                    $data['category_names'] = "";
                }
                if (isset($queryResult->$queryResponse->app_desc) && !empty($queryResult->$queryResponse->app_desc)) {
                    $data['app_desc'] = $queryResult->$queryResponse->app_desc;
                } else {
                    $data['app_desc'] = "";
                }
                if (isset($queryResult->$queryResponse->service_phone) && !empty($queryResult->$queryResponse->service_phone)) {
                    $data['service_phone'] = $queryResult->$queryResponse->service_phone;
                } else {
                    $data['service_phone'] = "";
                }
                if (isset($queryResult->$queryResponse->service_email) && !empty($queryResult->$queryResponse->service_email)) {
                    $data['service_email'] = $queryResult->$queryResponse->service_email;
                } else {
                    $data['service_email'] = "";
                }
                if (isset($queryResult->$queryResponse->safe_domains) && !empty($queryResult->$queryResponse->safe_domains)) {
                    $data['safe_domains'] = $queryResult->$queryResponse->safe_domains;
                } else {
                    $data['safe_domains'] = "";
                }
                if (isset($queryResult->$queryResponse->package_names) && !empty($queryResult->$queryResponse->package_names)) {
                    $data['package_names'] = $queryResult->$queryResponse->package_names;
                } else {
                    $data['package_names'] = "";
                }

                return ['status' => 200,'message' => '查询成功','data' => $data];
            } else {
                return ['status' => 202,'message' => $queryResult->$queryResponse->msg.'|'.$queryResult->$queryResponse->sub_code.'|'.$queryResult->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 小程序修改基础信息
     * @param $appId
     * @param $app_auth_token
     * @return array
     */
    public function aliPayOpenMiniBaseInfoModify($appId, $app_auth_token, $requestData)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.baseinfo.modify";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $queryRequest = new AlipayOpenMiniBaseinfoModifyRequest();
            if (isset($requestData['app_name']) && !empty($requestData['app_name'])) {
                $queryRequest->setAppName($requestData['app_name']);
            }
            if (isset($requestData['app_english_name']) && !empty($requestData['app_english_name'])) {
                $queryRequest->setAppEnglishName($requestData['app_english_name']);
            }
            if (isset($requestData['app_slogan']) && !empty($requestData['app_slogan'])) {
                $queryRequest->setAppSlogan($requestData['app_slogan']);
            }
            if (isset($requestData['app_logo']) && !empty($requestData['app_logo'])) {
                $queryRequest->setAppLogo("@".$requestData['app_logo']);
            }
            if (isset($requestData['app_desc']) && !empty($requestData['app_desc'])) {
                $queryRequest->setAppDesc($requestData['app_desc']);
            }
            if (isset($requestData['service_phone']) && !empty($requestData['service_phone'])) {
                $queryRequest->setServicePhone($requestData['service_phone']);
            }
            if (isset($requestData['service_email']) && !empty($requestData['service_email'])) {
                $queryRequest->setServiceEmail($requestData['service_email']);
            }
            if (isset($requestData['mini_category_ids']) && !empty($requestData['mini_category_ids'])) {
                $queryRequest->setMiniCategoryIds($requestData['mini_category_ids']);
            }

            $queryResult = $aop->execute($queryRequest, null, $app_auth_token);
            $queryResponse = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
            $queryResponseNode = $queryResult->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                return ['status' => 200,'message' => '修改成功'];
            } else {
                return ['status' => 202,'message' => $queryResult->$queryResponse->msg.'|'.$queryResult->$queryResponse->sub_code.'|'.$queryResult->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 小程序类目树查询
     * @param $appId
     * @param $app_auth_token
     * @return array
     */
    public function aliPayOpenMiniCategoryQuery($appId, $app_auth_token)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.mini.category.query";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';
            $queryRequest = new AlipayOpenMiniCategoryQueryRequest();
            $queryRequest->setBizContent("{" .
                "\"is_filter\":true" .
                "  }");
            $queryResult = $aop->execute($queryRequest, null, $app_auth_token);
            $queryResponse = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
            $queryResponseNode = $queryResult->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                $mini_category_list = $queryResult->$queryResponse->mini_category_list;
                return ['status' => 200,'message' => '查询成功','data' => $mini_category_list];
            } else {
                return ['status' => 202,'message' => $queryResult->$queryResponse->msg.'|'.$queryResult->$queryResponse->sub_code.'|'.$queryResult->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 对外请求方法 小程序退回开发 | 小程序结束灰度 | 小程序删除版本 | 小程序撤销审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenMiniVersionAuditedCancel(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['mini_app_id']) || empty($requestAllData['mini_app_id'])) {
            return $this->responseDataJson(202, "小程序appid不可为空");
        }

        if (!isset($requestAllData['app_version']) || empty($requestAllData['app_version'])) {
            return $this->responseDataJson(202, "小程序版本不可为空");
        }

        if (!isset($requestAllData['type']) || empty($requestAllData['type'])) {
            return $this->responseDataJson(202, "类型不可为空");
        }

        $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->first();

        if (empty($appletsInfo)) {
            return $this->responseDataJson(202, "该小程序暂未授权");
        }

        $result = $this->aliPayOpenMiniVersionAuditedCancel($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['app_version'], $requestAllData['type']);

        if ($result['status'] == 200) {
            return $this->responseDataJson(200, '操作成功');
        } else {
            return $this->responseDataJson($result['status'], $result['message']);
        }
    }

    /**
     * 封装 小程序退回开发 | 小程序结束灰度 | 小程序删除版本 | 小程序撤销审核
     * @param $appId
     * @param $app_auth_token
     * @param $app_version
     * @param $type
     * 1:小程序退回开发
     * 2:小程序结束灰度
     * 3:小程序删除版本
     * 4:小程序撤销审核
     * @return array
     */
    public function aliPayOpenMiniVersionAuditedCancel($appId, $app_auth_token, $app_version, $type)
    {
        try {
            $method                     = "";
            switch ($type) {
                case 1:
                    $aop = new AopClient();
                    $method             = "alipay.open.mini.version.audited.cancel";
                    break;
                case 2:
                    $aop = new AopClient();
                    $method             = "alipay.open.mini.version.gray.cancel";
                    break;
                case 3:
                    $aop = new AopClient();
                    $method             = "alipay.open.mini.version.delete";
                    break;
                case 4:
                    $aop = new AopClient2019();
                    $method             = "alipay.open.mini.version.audit.cancel";
                    break;
            }

            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = $method;

            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            switch ($type) {
                case 1:
                    $queryRequest = new AlipayOpenMiniVersionAuditedCancelRequest();
                    break;
                case 2:
                    $queryRequest = new AlipayOpenMiniVersionGrayCancelRequest();
                    break;
                case 3:
                    $queryRequest = new AlipayOpenMiniVersionDeleteRequest();
                    break;
                case 4:
                    $queryRequest = new AlipayOpenMiniVersionAuditCancelRequest();
                    break;
            }

            $queryRequest->setBizContent("{" .
                "\"app_version\":\"".$app_version."\"," .
                "\"bundle_id\":\"com.alipay.alipaywallet\"" .
                "  }");
            $queryResult = $aop->execute($queryRequest, null, $app_auth_token);
            $queryResponse = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
            $queryResponseNode = $queryResult->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                return ['status' => 200,'message' => '操作成功'];
            } else {
                return ['status' => 202,'message' => $queryResult->$queryResponse->msg.'|'.$queryResult->$queryResponse->sub_code.'|'.$queryResult->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 发送模板消息
     * @param $appId
     * @param $app_auth_token
     * @param $to_user_id
     * @return array
     *
     * //$request->setBizContent("{" .
       //    "\"to_user_id\":\"".$to_user_id."\"," .
       //    "\"form_id\":\"".$form_id."\"," .
       //    "\"user_template_id\":\"".$template_id."\"," .
       //    "\"page\":\"page/index/index?store_id=".$store_id."\"," .
       //    "\"data\":\"{\\\"keyword1\\\": {\\\"value\\\" : \\\"asd\\\"},\\\"keyword2\\\": {\\\"value\\\" : \\\"领取优惠券\\\"},}\"" .
       //    "  }");
     *
     */
    public function aliPayOpenAppMiniTemplateMessageSend($appId, $app_auth_token, $store_id, $to_user_id, $formId, $templateId, $templateData)
    {
        try {
            $aop = new AopClient();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.app.mini.templatemessage.send";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';

            $request = new AlipayOpenAppMiniTemplatemessageSendRequest();

            $params1 = [
                'to_user_id'       => $to_user_id,
                'form_id'          => $formId,
                'user_template_id' => $templateId,
                'page'             => '/pages/index/index?store_id='.$store_id,
                'data'             => $templateData
            ];

            $json_template = json_encode($params1);

            $request->setBizContent(urldecode($json_template));
            $result = $aop->execute($request, null, $app_auth_token);
            $queryResponse = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $queryResponseNode = $result->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                return ['status' => 200,'message' => '操作成功'];
            } else {
                return ['status' => 202,'message' => $result->$queryResponse->msg.'|'.$result->$queryResponse->sub_code.'|'.$result->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 保存formId, 发送模板消息时使用
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveFormId(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])) {
            return $this->responseDataJson(202, "小程序store_id不可为空");
        }

        if (!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])) {
            return $this->responseDataJson(202, "user_id不可为空");
        }

        if (!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])) {
            return $this->responseDataJson(202, "类型不可为空");
        }

        if (!isset($requestAllData['formId']) || empty($requestAllData['formId'])) {
            return $this->responseDataJson(202, "formId不可为空");
        }

        $system_user_id = "";
        if (!isset($requestAllData['system_user_id']) || empty($requestAllData['system_user_id'])) {
            $model = $this->weChatOrAliPayRequest($requestAllData['terminal_type']);
            $userInfoResult = $model->getUserInfo($requestAllData['user_id'], $requestAllData['store_id']);
            switch ($requestAllData['terminal_type']) {
                case config("api.weChat"):
                    $system_user_id = $userInfoResult->wechat_openid;
                    break;
                case config("api.aliPay"):
                    $system_user_id = $userInfoResult->alipay_user_id;
                    break;
            }
        } else {
            $system_user_id = $requestAllData['system_user_id'];
        }

        $formIdData = [
            'store_id'  => $requestAllData['store_id'],
            'user_id'   => $requestAllData['user_id'],
            'system_id' => $system_user_id,
            'type'      => $requestAllData['terminal_type'] == config("api.weChat") ? 1 : 2,
            'is_use'    => 1,
            'form_id'   => $requestAllData['formId'],
            'created_at'=> date("Y-m-d H:i:s", time()),
            'updated_at'=> date("Y-m-d H:i:s", time())
        ];
        $result = DB::table("customerapplets_form_ids")->insert($formIdData);
        if ($result) {
            return $this->responseDataJson(200, "保存成功");
        } else {
            return $this->responseDataJson(202, "保存失败");
        }
    }

    /**
     * 根据小程序名称搜索小程序的appid
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAppletAppId(Request $request)
    {
        $requestAllData = $request->all();
        if (!isset($requestAllData['applet_name']) || empty($requestAllData['applet_name'])) {
            return $this->responseDataJson(202, "applet_name不可为空");
        }
        $result = DB::table("customerapplets_authorize_appids")->select("id", "t_appid", "AuthorizerAppid")->where([
            'applet_name' => $requestAllData['applet_name'],
            'applet_type' => 2,
        ])->first();
        if ($result) {
            return $this->responseDataJson(200, "查询成功", $result);
        } else {
            return $this->responseDataJson(202, "未查询到");
        }
    }

    /**
     * 获取支付宝小程序模板列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTemplateListData(Request $request)
    {
        $requestAllData = $request->all();
        $page = $requestAllData['page'];
        $count = isset($requestAllData['count']) ? $requestAllData['count'] : 10;
        // $total_count = DB::table("customerapplets_template_infos")
        //     ->where(['applet_id' => config('api.aliPay_applet_template_id'),'type' => 2])->count();
        // $result = DB::table("customerapplets_template_infos")
        //     ->where(['applet_id' => config('api.aliPay_applet_template_id'),'type' => 2])
        //     ->paginate(10)->toArray();
        $total_count = DB::table("customerapplets_template_infos")
            ->where(['applet_id' => $this->aliPay_applet_template_id,'type' => 2])->count();
        $result = DB::table("customerapplets_template_infos")
            ->where(['applet_id' => $this->aliPay_applet_template_id,'type' => 2])
            ->paginate(10)->toArray();
        // aliPay_applet_template_id

        return response()->json([
            'status'  => 200,
            'message' => "请求成功",
            'data'    => isset($result) ? $result['data'] : [],
            'total_count' => $total_count,
            'page'    => (int)$page,
            't'       => (int)$count,
        ]);
    }

    /**
     * 保存支付宝小程序模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addTemplateListData(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['applet_id']) || empty($requestAllData['applet_id'])) {
            return $this->responseDataJson(202, "applet_id不可为空");
        }
        if (!isset($requestAllData['title']) || empty($requestAllData['title'])) {
            return $this->responseDataJson(202, "title不可为空");
        }
        if (!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])) {
            return $this->responseDataJson(202, "template_id不可为空");
        }
        if (!isset($requestAllData['template_keyword']) || empty($requestAllData['template_keyword'])) {
            return $this->responseDataJson(202, "template_keyword不可为空");
        }

        $templateData['applet_id']   = $requestAllData['applet_id'];
        $templateData['type']        = 2;
        $templateData['title']       = $requestAllData['title'];
        $templateData['template_id'] = $requestAllData['template_id'];
        $templateData['status']      = 1;
        $templateData['template_keyword'] = $requestAllData['template_keyword'];
        $templateData['created_at']  = date("Y-m-d H:i:s", time());
        $templateData['updated_at']  = date("Y-m-d H:i:s", time());

        $result = DB::table("customerapplets_template_infos")->insert($templateData);
        if ($result) {
            return $this->responseDataJson(200, "保存成功");
        } else {
            return $this->responseDataJson(202, "保存失败");
        }
    }

    /**
     * 修改支付宝小程序模板
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateTemplateListData(Request $request)
    {
        $requestAllData = $request->all();

        if (!isset($requestAllData['id']) || empty($requestAllData['id'])) {
            return $this->responseDataJson(202, "id不可为空");
        }
        if (!isset($requestAllData['applet_id']) || empty($requestAllData['applet_id'])) {
            return $this->responseDataJson(202, "applet_id不可为空");
        }
        if (!isset($requestAllData['title']) || empty($requestAllData['title'])) {
            return $this->responseDataJson(202, "title不可为空");
        }
        if (!isset($requestAllData['template_id']) || empty($requestAllData['template_id'])) {
            return $this->responseDataJson(202, "template_id不可为空");
        }
        if (!isset($requestAllData['template_keyword']) || empty($requestAllData['template_keyword'])) {
            return $this->responseDataJson(202, "template_keyword不可为空");
        }
        if (!isset($requestAllData['status']) || empty($requestAllData['status'])) {
            return $this->responseDataJson(202, "status不可为空");
        }

        $templateData['applet_id']   = $requestAllData['applet_id'];
        $templateData['title']       = $requestAllData['title'];
        $templateData['template_id'] = $requestAllData['template_id'];
        $templateData['status']      = $requestAllData['status'];
        $templateData['template_keyword'] = $requestAllData['template_keyword'];
        $templateData['updated_at']  = date("Y-m-d H:i:s", time());

        $result = DB::table("customerapplets_template_infos")->where(['id' => $requestAllData['id']])->update($templateData);
        if ($result) {
            return $this->responseDataJson(200, "修改成功");
        } else {
            return $this->responseDataJson(202, "修改失败");
        }
    }

    /**
     * 对外请求方法 授权应用aes密钥查询
     * 如果未查询到，就进行设置aesKey密钥
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenAuthAppAesGet(Request $request)
    {
        $requestAllData = $request->all();
        if (!isset($requestAllData['mini_app_id']) || empty($requestAllData['mini_app_id'])) {
            return $this->responseDataJson(202, "小程序appid不可为空");
        }
        $appletsInfo = DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->first();
        if (empty($appletsInfo)) {
            return $this->responseDataJson(202, "该小程序暂未授权");
        }
        $result = $this->aliPayOpenAuthAppAesGet($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['mini_app_id']);

        if ($result['status'] == 200) {
            if (isset($result['aesKey']) && !empty($result['aesKey'])) {
                DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->update([
                    'aliPay_aes' => $result['aesKey'],
                    'updated_at' => date("Y-m-d H:i:s", time())
                ]);
                return $this->responseDataJson(200, '操作成功', ['aesKey' => $result['aesKey']]);
            } else {
                $setResult = $this->aliPayOpenAuthAppAesSet($appletsInfo->t_appid, $appletsInfo->AuthorizationCode, $requestAllData['mini_app_id']);
                if (isset($setResult['aesKey']) && !empty($setResult['aesKey'])) {
                    DB::table("customerapplets_authorize_appids")->where(['applet_type' => 2,'AuthorizerAppid' => $requestAllData['mini_app_id']])->update([
                        'aliPay_aes' => $setResult['aesKey'],
                        'updated_at' => date("Y-m-d H:i:s", time())
                    ]);
                    return $this->responseDataJson(200, '操作成功', ['aesKey' => $setResult['aesKey']]);
                } else {
                    return $this->responseDataJson($setResult['status'], $setResult['message']);
                }
            }
        } else {
            return $this->responseDataJson($result['status'], $result['message']);
        }
    }

    /**
     * 封装 授权应用aes密钥查询
     * 注意：第三方调用该接口不需要传入app_auth_token
     * @param $appId
     * @param $app_auth_token
     * @param $merchant_app_id
     * @return array
     */
    public function aliPayOpenAuthAppAesGet($appId, $app_auth_token, $merchant_app_id)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.auth.app.aes.get";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';
            // $aop->encryptKey            = config('api.aesKey');
            $aop->encryptKey            = $this->ali_aesKey;
            $aop->encryptType           = "AES";

            $request = new AlipayOpenAuthAppAesGetRequest();
            $request->setBizContent("{" .
                "\"merchant_app_id\":\"".$merchant_app_id."\"" .
                "  }");

//            $result = $aop->execute($request,null,$app_auth_token);
            $result = $aop->execute($request);
            $queryResponse = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $queryResponseNode = $result->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                $aesKey = isset($result->$queryResponse->aes_key) ? $result->$queryResponse->aes_key : "";

                return ['status' => 200,'message' => '操作成功','aesKey' => $aesKey];
            } else {
                return ['status' => 202,'message' => $result->$queryResponse->msg.'|'.$result->$queryResponse->sub_code.'|'.$result->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 封装 授权应用aes密钥设置
     * 注意：第三方调用该接口不需要传入app_auth_token
     * @param $appId
     * @param $app_auth_token
     * @param $merchant_app_id
     * @return array
     */
    public function aliPayOpenAuthAppAesSet($appId, $app_auth_token, $merchant_app_id)
    {
        try {
            $aop = new AopClient2019();
            $aop->gatewayUrl            = 'https://openapi.alipay.com/gateway.do';
            $aop->appId                 = $appId;
            $aop->method                = "alipay.open.auth.app.aes.set";
            $aop->charset               = "utf-8";
            $aop->timestamp             = date("Y-m-d H:i:s", time());
            $aop->rsaPrivateKey         = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey    = $this->rsaPublicKey;
            $aop->apiVersion            = '1.0';
            $aop->signType              = 'RSA2';
            $aop->postCharset           = 'utf-8';
            $aop->format                = 'json';
            // $aop->encryptKey            = config('api.aesKey');
            $aop->encryptKey            = $this->ali_aesKey;
            $aop->encryptType           = "AES";

            $request = new AlipayOpenAuthAppAesSetRequest();
            $request->setBizContent("{" .
                "\"merchant_app_id\":\"".$merchant_app_id."\"" .
                "  }");

//            $result = $aop->execute($request,null,$app_auth_token);
            $result = $aop->execute($request);
            $queryResponse = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $queryResponseNode = $result->$queryResponse->code;
            if (!empty($queryResponseNode) && $queryResponseNode == 10000) {
                $aesKey = isset($result->$queryResponse->aes_key) ? $result->$queryResponse->aes_key : "";

                return ['status' => 200,'message' => '操作成功','aesKey' => $aesKey];
            } else {
                return ['status' => 202,'message' => $result->$queryResponse->msg.'|'.$result->$queryResponse->sub_code.'|'.$result->$queryResponse->sub_msg];
            }
        } catch (\Exception $e) {
            return ['status' => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 获取支付宝第三方app_id的方法
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliPayOpenAppletId()
    {
        // $appId = config('api.aliPay_applet_id');
        $appId = $this->ali_appid;
        return $this->responseDataJson(200, "获取成功", ["app_id" => $appId]);
    }
}
